// frontend/src/admin/CheckinManagement.js

import React, { useState, useEffect, useCallback } from 'react';
import { Table, Button, Modal, Form, Input, Select, DatePicker, message, Space, Popconfirm } from 'antd';
import { adminAPI } from '../services/api';
import moment from 'moment';

const { Option } = Select;

const CheckinManagement = () => {
  const [form] = Form.useForm();
  const [checkins, setCheckins] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [guests, setGuests] = useState([]);
  const [rooms, setRooms] = useState([]);
  const [filterParams, setFilterParams] = useState({});

  // 使用 useCallback 包装 fetchCheckins 和 fetchRooms，避免不必要的重新创建函数
  const fetchCheckins = useCallback(async () => {
    setLoading(true);
    try {
      const params = {
        ...filterParams,
        limit: pagination.pageSize,
        offset: (pagination.current - 1) * pagination.pageSize,
      };
      const response = await adminAPI.getAllCheckins(params);
      // 确保 response.data.data 存在
      setCheckins(response.data.data || []);
      setPagination(prev => ({ ...prev, total: response.data.total }));
    } catch (error) {
      message.error('获取入住记录失败: ' + (error.response?.data?.message || error.message));
      console.error('Error fetching checkins:', error);
    } finally {
      setLoading(false);
    }
  }, [filterParams, pagination.current, pagination.pageSize]); // 添加所有依赖项

  const fetchGuests = useCallback(async () => {
    try {
      const response = await adminAPI.searchGuests({}); // 获取所有客户用于选择
      setGuests(response.data || []); // 确保返回的是数组
    } catch (error) {
      message.error('获取客户列表失败: ' + (error.response?.data?.message || error.message));
      console.error('Error fetching guests:', error);
    }
  }, []);

  const fetchRooms = useCallback(async () => {
    try {
      const response = await adminAPI.getAvailableRooms(); // 获取可用房间用于选择
      // 核心修改：确保将 response.data 设置给 rooms，并检查是否为数组
      setRooms(Array.isArray(response.data) ? response.data : []);
    } catch (error) {
      message.error('获取可用房间列表失败: ' + (error.response?.data?.message || error.message));
      console.error('Error fetching available rooms:', error);
    }
  }, []);

  useEffect(() => {
    fetchCheckins();
    fetchGuests();
    fetchRooms();
  }, [fetchCheckins, fetchGuests, fetchRooms]);

  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
  };

  const showModal = () => {
    form.resetFields();
    form.setFieldsValue({
      check_in_time: moment() // 设置默认入住时间为当前时间
    });
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const onFinish = async (values) => {
    try {
      const formattedValues = {
        ...values,
        check_in_time: values.check_in_time ? values.check_in_time.format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm:ss'),
      };

      await adminAPI.createCheckin(formattedValues);
      message.success('入住办理成功');
      form.resetFields();
      setIsModalVisible(false);
      fetchCheckins(); // 刷新列表
      fetchRooms(); // 刷新房间状态
    } catch (error) {
      message.error('办理入住失败: ' + (error.response?.data?.message || error.message));
      console.error('Error creating checkin:', error);
    }
  };

  const handleCheckout = async (checkinId) => {
    try {
      const checkoutTime = moment().format('YYYY-MM-DD HH:mm:ss');
      // 注意：这里是 PUT 请求到 /api/admin/checkins/:id/checkout
      await adminAPI.checkout(checkinId, { check_out_time: checkoutTime });
      message.success('退房成功');
      fetchCheckins();
      fetchRooms();
    } catch (error) {
      message.error('退房失败: ' + (error.response?.data?.message || error.message));
      console.error('Error during checkout:', error);
    }
  };

  const onSearch = (values) => {
    const newFilterParams = {
      ...values,
      startDate: values.startDate ? values.startDate.format('YYYY-MM-DD') : undefined,
      endDate: values.endDate ? values.endDate.format('YYYY-MM-DD') : undefined,
    };
    setFilterParams(newFilterParams);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  const columns = [
    { title: '房间号', dataIndex: 'room_number', key: 'room_number' },
    { title: '客户姓名', dataIndex: 'guest_name', key: 'guest_name' },
    { title: '身份证号', dataIndex: 'id_card', key: 'id_card' },
    { title: '房间类型', dataIndex: 'room_type', key: 'room_type' },
    { title: '房间价格', dataIndex: 'room_price', key: 'room_price' },
    {
      title: '入住时间',
      dataIndex: 'checkin_date',
      key: 'checkin_date',
      render: (text) => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '',
    },
    {
      title: '退房时间',
      dataIndex: 'checkout_date',
      key: 'checkout_date',
      render: (text) => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '',
    },
    { title: '状态', dataIndex: 'status', key: 'status' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
          <Space size="middle">
            {record.status === '入住中' && (
                <Popconfirm
                    title="确定要办理退房吗？"
                    onConfirm={() => handleCheckout(record.checkin_id)}
                    okText="是"
                    cancelText="否"
                >
                  <Button type="danger">退房</Button>
                </Popconfirm>
            )}
          </Space>
      ),
    },
  ];

  return (
      <div style={{ padding: 24 }}>
        <h2>入住管理</h2>
        <Form layout="inline" onFinish={onSearch} style={{ marginBottom: 16 }}>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 120 }} allowClear>
              <Option value="入住中">入住中</Option>
              <Option value="已退房">已退房</Option>
            </Select>
          </Form.Item>
          <Form.Item name="room_number" label="房间号">
            <Input placeholder="输入房间号" />
          </Form.Item>
          <Form.Item name="guest_name" label="客户姓名">
            <Input placeholder="输入客户姓名" />
          </Form.Item>
          <Form.Item name="id_card" label="身份证号">
            <Input placeholder="输入身份证号" />
          </Form.Item>
          <Form.Item name="startDate" label="开始日期">
            <DatePicker />
          </Form.Item>
          <Form.Item name="endDate" label="结束日期">
            <DatePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={showModal}>
              办理入住
            </Button>
          </Form.Item>
        </Form>

        <Table
            columns={columns}
            dataSource={checkins}
            rowKey="checkin_id"
            loading={loading}
            pagination={pagination}
            onChange={handleTableChange}
        />

        <Modal
            title="办理入住"
            open={isModalVisible} // 使用 open 替代 visible
            onCancel={handleCancel}
            footer={null}
        >
          <Form
              form={form}
              layout="vertical"
              onFinish={onFinish}
          >
            <Form.Item
                name="guest_id"
                label="选择客户"
                rules={[{ required: true, message: '请选择客户' }]}
            >
              <Select
                  showSearch
                  placeholder="选择客户 (姓名 - 身份证号)"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                      // 确保 option.children 是字符串
                      String(option.children || '').toLowerCase().includes(input.toLowerCase())
                  }
              >
                {guests.map(guest => (
                    <Option key={guest.guest_id} value={guest.guest_id}>
                      {guest.name} - {guest.id_card}
                    </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
                name="room_id"
                label="选择房间"
                rules={[{ required: true, message: '请选择房间' }]}
            >
              <Select
                  showSearch
                  placeholder="选择房间 (房间号 - 价格)"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                      // 确保 option.children 是字符串
                      String(option.children || '').toLowerCase().includes(input.toLowerCase())
                  }
              >
                {/* 确保 rooms 数组有数据且每个元素有 room_number 和 price 属性 */}
                {rooms.map(room => (
                    <Option key={room.room_id} value={room.room_id}>
                      {room.room_number} - ¥{parseFloat(room.price).toFixed(2)}
                    </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
                name="check_in_time"
                label="入住时间"
                rules={[{ required: true, message: '请选择入住时间' }]}
            >
              <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                办理入住
              </Button>
              <Button onClick={handleCancel} style={{ marginLeft: 8 }}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
  );
};

export default CheckinManagement;